<template>
  <Dialog width="80%" :title="dialogTitle" v-model="dialogVisible" @close="onReset">
    <eleForm
      ref="addForm"
      :slotShow="false"
      :form-data="formData"
      :form-columns="formColumns"
      :form-rules="formRules"
      label-width="120px"
    >
    </eleForm>

    <template #footer>
      <el-button @click="onSubmit" type="primary" :disabled="formLoading">确 定 {{ isEdit }}</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import eleForm from '@/components/MyForm/index.vue'
import * as ProjectApi from '@/api/project/baseData/index'
import { formColumns, initData, editData, formRules, formColumnsDisabledHanadle } from './data'


// 消息弹窗
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const message = useMessage()

// 将表单绑定的ref暴露给父组件
let formData = reactive(initData)
const addForm = ref<any>(null)
const isEdit = ref(false) // 是否是修改操作

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = type == 'create' ? '新增' : '编辑'
  isEdit.value = !!id
  // 修改表单配置项禁用
  formColumnsDisabledHanadle('businessType', 'disabled', isEdit.value )
  await nextTick()
  if (id) {
    const data = await ProjectApi.getProjectBaseData(id)
    data.startTime = "2023-12-31T16:00:00.000Z"
    data.endTime = "2023-12-31T16:00:00.000Z"
    formData = Object.assign(formData, data)
  }
}

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

// 提交操作
const onSubmit = async () => {
  let isValidate = await addForm.value.formSubmit()
  if(!isValidate) return;
  if(!isEdit.value){
    await ProjectApi.createProjectBaseData(formData)
    message.success("添加成功")
  }else{
    await ProjectApi.updateProjectBaseData(formData)
    message.success("修改成功")
  }
  // 重置数据
  onReset()
  dialogVisible.value = false
  // 发送操作成功的事件
  emit('success')
}

// 重置操作
const onReset = async () => {
  addForm.value.formReset()
}

// 提供 open 方法，用于打开弹窗
defineExpose({ open })
</script>
